package com.haohan.cloud.scm.supply.core.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haohan.cloud.scm.api.constant.enums.supply.PdsOfferStatusEnum;
import com.haohan.cloud.scm.api.constant.enums.supply.PdsOfferTypeEnum;
import com.haohan.cloud.scm.api.constant.enums.supply.ShipStatusEnum;
import com.haohan.cloud.scm.api.goods.dto.GoodsModelDTO;
import com.haohan.cloud.scm.api.goods.entity.GoodsModel;
import com.haohan.cloud.scm.api.goods.feign.GoodsModelFeignService;
import com.haohan.cloud.scm.api.goods.req.GoodsModelReq;
import com.haohan.cloud.scm.api.purchase.entity.PurchaseOrderDetail;
import com.haohan.cloud.scm.api.purchase.feign.PurchaseOrderDetailFeignService;
import com.haohan.cloud.scm.api.purchase.req.PurchaseOrderDetailReq;
import com.haohan.cloud.scm.api.supply.entity.OfferOrder;
import com.haohan.cloud.scm.api.supply.entity.Supplier;
import com.haohan.cloud.scm.api.supply.entity.SupplierAgreement;
import com.haohan.cloud.scm.api.supply.req.*;
import com.haohan.cloud.scm.api.supply.resp.QueryGoodsStorageResp;
import com.haohan.cloud.scm.api.supply.trans.OfferOrderTrans;
import com.haohan.cloud.scm.common.tools.exception.EmptyDataException;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.haohan.cloud.scm.supply.core.IScmSupplyOrderService;
import com.haohan.cloud.scm.supply.service.OfferOrderService;
import com.haohan.cloud.scm.supply.service.SupplierAgreementService;
import com.haohan.cloud.scm.supply.service.SupplierService;
import com.haohan.cloud.scm.supply.utils.ScmSupplyUtils;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 * 报价单管理
 *
 * @author xwx
 * @date 2019/5/15.
 */
@Service
@AllArgsConstructor
public class ScmSupplyOrderServiceImpl implements IScmSupplyOrderService {
    private final OfferOrderService offerOrderService;
    private final SupplierService supplierService;
    private final PurchaseOrderDetailFeignService purchaseOrderDetailFeignService;
    private final GoodsModelFeignService goodsModelFeignService;
    private final SupplierAgreementService supplierAgreementService;
    private final ScmSupplyUtils scmSupplyUtils;

    /**
     * 查询供应商品库存信息列表
     *
     * @param req
     * @return
     */
    @Override
    public Page<QueryGoodsStorageResp> querySupplyGoodsRepertoryList(QueryGoodsRepertoryListReq req) {
        //查询协议供应商品列表
        Page page = new Page(req.getPageNo(), req.getPageSize());
        SupplierAgreement supplierAgreement = new SupplierAgreement();
        supplierAgreement.setPmId(req.getPmId());
        supplierAgreement.setSupplierId(req.getSupplierId());
        IPage iPage = supplierAgreementService.page(page, Wrappers.query(supplierAgreement));
        //关联商品规格
        List<QueryGoodsStorageResp> list = new ArrayList<>();
        for (SupplierAgreement agreement : (List<SupplierAgreement>) iPage.getRecords()) {
            GoodsModelDTO dto = scmSupplyUtils.fetchGoodsModelDTO(agreement.getGoodsModelId());
            QueryGoodsStorageResp res = new QueryGoodsStorageResp();
            BeanUtil.copyProperties(dto,res);
            res.setAgreementId(agreement.getId());
            list.add(res);
        }
        Page<QueryGoodsStorageResp> goodsModelPage = new Page<>();
        goodsModelPage.setCurrent(iPage.getCurrent());
        goodsModelPage.setSize(iPage.getSize());
        goodsModelPage.setTotal(iPage.getTotal());
        goodsModelPage.setPages(iPage.getPages());
        goodsModelPage.setRecords(list);
        return goodsModelPage;
    }

    /**
     * 查询供应商品库存详情
     *
     * @param req
     * @return
     */
    @Override
    public GoodsModel querySupplyGoodsRepertory(QueryGoodsRepertoryDetailReq req) {
        SupplierAgreement supplierAgreement = new SupplierAgreement();
        supplierAgreement.setId(req.getId());
        supplierAgreement.setPmId(req.getPmId());
        SupplierAgreement agreement = supplierAgreementService.getOne(Wrappers.query(supplierAgreement));
        if (agreement == null) {
            throw new ErrorDataException("agreement为空");
        }
        //关联商品规格
        GoodsModelReq goodsModelReq = new GoodsModelReq();
        goodsModelReq.setId(agreement.getGoodsModelId());
        GoodsModel goodsModel = scmSupplyUtils.fetchGoodsModel(goodsModelReq);
        return goodsModel;
    }

    /**
     * 新增货源报价
     *
     * @param req
     * @return
     */
    @Override
    public OfferOrder addSupplierOffer(OfferOrderReq req) {
        OfferOrder offerOrder = quotationCurrent(req);
        //报价类型 货源报价
        offerOrder.setOfferType(PdsOfferTypeEnum.supplierOffer);
        //报价状态 已报价
        offerOrder.setStatus(PdsOfferStatusEnum.alreadyOffer);
        offerOrderService.save(offerOrder);
        return offerOrder;
    }


    /**
     * 供应商报价  (新增报价单 竞价采购)
     *
     * @param req 商品规格id、供应商id、采购单明细id
     * @return
     */
    @Override
    public OfferOrder addOfferBySupplier(OfferOrderReq req) {
        OfferOrder offerOrder = quotationCurrent(req);

        //报价类型 竞价采购
        offerOrder.setOfferType(PdsOfferTypeEnum.bazaarOffer);
        //报价状态 已报价
        offerOrder.setStatus(PdsOfferStatusEnum.alreadyOffer);

        offerOrderService.save(offerOrder);
        return offerOrder;
    }

    /**
     * 采购员挑选供应商  (新增报价单  单品采购)
     *
     * @param req 商品规格id、供应商id、采购单明细id
     * @return
     */
    @Override
    public OfferOrder addOfferByPurchase(OfferOrderReq req) {
        OfferOrder offerOrder = quotationCurrent(req);
        //报价类型 单品采购
        offerOrder.setOfferType(PdsOfferTypeEnum.platformOffer);
        //报价状态 中标
        offerOrder.setStatus(PdsOfferStatusEnum.bidding);

        offerOrderService.save(offerOrder);

        return offerOrder;
    }

    /**
     * 根据供应协议设置供应商 (新增报价单 协议采购)
     *
     * @param req 商品规格id、供应商id、采购单明细id
     * @return
     */
    @Override
    public OfferOrder addOfferByAgreement(OfferOrderReq req) {
        OfferOrder offerOrder = quotationCurrent(req);
        //报价类型 协议采购
        offerOrder.setOfferType(PdsOfferTypeEnum.appointOffer);
        //报价状态 中标
        offerOrder.setStatus(PdsOfferStatusEnum.bidding);

        offerOrderService.save(offerOrder);
        return offerOrder;
    }

    /**
     * 初始创建报价单(不包括货源报价)
     *
     * @param req 必需参数: supplierId / supplyPrice / offerType / goodsModelId
     * @return
     */
    @Override
    public OfferOrder addOfferOrder(AddOfferOrderReq req) {
        OfferOrder offerOrder = new OfferOrder();
        // 可选属性直接传入
        BeanUtil.copyProperties(req, offerOrder);
        // 状态/时间设置
        if(null == offerOrder.getStatus()){
            offerOrder.setStatus(PdsOfferStatusEnum.alreadyOffer);
        }
        offerOrder.setOfferPriceTime(LocalDateTime.now());
        // 供应商信息
        Supplier supplier = fetchSupplier(req.getSupplierId());
        offerOrder.setPmId(supplier.getPmId());
        offerOrder.setSupplierName(supplier.getSupplierName());
        // 商品信息
        GoodsModelDTO goodsModel = fetchGoodsModel(req.getGoodsModelId());
        OfferOrderTrans.copyFromGoodsModelDTO(offerOrder, goodsModel);
        if (!offerOrderService.save(offerOrder)) {
            throw new ErrorDataException("报价单保存失败");
        }
        return offerOrder;
    }

    /**
     * 查询供应商货源（加筛选条件）
     * @param req
     * @return
     */
    @Override
    public Page<OfferOrder> filterOfferOrder(FilterOfferOrderReq req) {
        List<OfferOrder> list = new ArrayList<>();
        Page page = new Page(req.getCurrent(), req.getSize());
        if (null!=req.getSupplierLevel()){
            Supplier supplierReq = new Supplier();
            BeanUtil.copyProperties(req,supplierReq);
            List<Supplier> supplierList = supplierService.list(Wrappers.query(supplierReq));
            for (Supplier supplier : supplierList) {
                OfferOrder offerOrderReq = new OfferOrder();
                offerOrderReq.setPmId(req.getPmId());
                offerOrderReq.setGoodsCategoryId(req.getGoodsCategoryId());
                offerOrderReq.setSupplierId(supplier.getId());
                List<OfferOrder> offerOrderList = offerOrderService.list(Wrappers.query(offerOrderReq));
                for (OfferOrder offerOrder : offerOrderList){
                    list.add(offerOrder);
                }
            }
            page.setRecords(list);
        }else {
            OfferOrder offerOrderReq = new OfferOrder();
            BeanUtil.copyProperties(req,offerOrderReq);
            IPage p = offerOrderService.page(page, Wrappers.query(offerOrderReq));
            page.setRecords(p.getRecords());
        }
        return page;
    }

    /**
     * 供应商报价
     * @param req
     * @return
     */
    @Override
    public Boolean affirmOffer(AffirmOfferReq req) {
        Supplier supplier = scmSupplyUtils.fetchByUid(req.getPmId(), req.getUid());
        if (null==supplier){
            throw new EmptyDataException("没有这个供应商");
        }
        OfferOrder offerOrder = new OfferOrder();
        offerOrder.setPmId(req.getPmId());
        offerOrder.setId(req.getId());
        offerOrder.setSupplierId(supplier.getId());
        offerOrder.setOfferType(PdsOfferTypeEnum.bazaarOffer);
        offerOrder.setStatus(PdsOfferStatusEnum.stayOffer);
        OfferOrder one = offerOrderService.getOne(Wrappers.query(offerOrder));
        if (null==one){
            throw new EmptyDataException("没有这个报价单");
        }
        OfferOrder updateOrder = new OfferOrder();
        updateOrder.setId(one.getId());
        updateOrder.setSupplyPrice(req.getSupplyPrice());
        updateOrder.setReceiveType(req.getReceiveType());
        updateOrder.setRemarks(req.getRemarks());
        updateOrder.setStatus(PdsOfferStatusEnum.alreadyOffer);
        updateOrder.setOfferPriceTime(LocalDateTime.now());
        if (!offerOrderService.updateById(updateOrder)){
            throw new ErrorDataException("修改失败");
        }
        return true;
    }

    /**
     * 修改报价单
     * @param req
     * @return
     */
    @Override
    public Boolean updateOfferOrder(UpdateOfferOrderReq req) {
        Supplier supplier = scmSupplyUtils.fetchByUid(req.getPmId(), req.getUid());
        if (null==supplier){
            throw new EmptyDataException("没有这个供应商");
        }
        OfferOrder offerOrder = new OfferOrder();
        offerOrder.setPmId(req.getPmId());
        offerOrder.setId(req.getId());
        offerOrder.setSupplierId(supplier.getId());
        offerOrder.setShipStatus(req.getShipStatus());
        OfferOrder one = offerOrderService.getOne(Wrappers.query(offerOrder));
        if (null==one){
            throw new EmptyDataException("没有这个报价单");
        }
        OfferOrder updateOrder = new OfferOrder();
        updateOrder.setId(one.getId());
        if (req.getShipStatus()==ShipStatusEnum.stayCargo){
            updateOrder.setShipStatus(ShipStatusEnum.startCargo);
        }
        if (req.getShipStatus()==ShipStatusEnum.startCargo){
            updateOrder.setShipStatus(ShipStatusEnum.sendCargo);
        }
        if (!offerOrderService.updateById(updateOrder)){
            throw new ErrorDataException("修改失败");
        }
        return true;
    }


    /**
     * 查询供应商
     *
     * @param id
     * @return
     */
    private Supplier fetchSupplier(String id) {
        Supplier supplier = supplierService.getById(id);
        if (supplier == null) {
            throw new ErrorDataException("supplier为空");
        }
        return supplier;
    }

    /**
     * 商品规格信息
     *
     * @param goodsModelId
     * @return
     */
    private GoodsModelDTO fetchGoodsModel(String goodsModelId) {
        R infoById = goodsModelFeignService.getInfoById(goodsModelId, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(infoById)) {
            throw new ErrorDataException("GoodsModel为空");
        }
        return BeanUtil.toBean(infoById.getData(), GoodsModelDTO.class);
    }

    /**
     * 报价单通用数据
     *
     * @param req
     * @return
     */
    public OfferOrder quotationCurrent(OfferOrderReq req) {
        OfferOrder offerOrder = new OfferOrder();
        BeanUtil.copyProperties(req, offerOrder);
        // 关联供应商
        Supplier supplier = fetchSupplier(req.getSupplierId());
        //获取供应商名称
        offerOrder.setSupplierName(supplier.getSupplierName());
        // 关联商品规格
        GoodsModelDTO goodsModel = fetchGoodsModel(req.getGoodsModelId());
        //规格名称
        offerOrder.setModelName(goodsModel.getModelName());
        offerOrder.setGoodsId(goodsModel.getGoodsId());
        //商品图片
        offerOrder.setGoodsImg(goodsModel.getModelUrl());
        //商品名称
        offerOrder.setGoodsName(goodsModel.getGoodsName());

        // 关联采购单明细
        PurchaseOrderDetailReq purchaseOrderDetailReq = new PurchaseOrderDetailReq();
        purchaseOrderDetailReq.setPurchaseDetailSn(req.getPurchaseDetailSn());
        R r = purchaseOrderDetailFeignService.getOneByPurchaseOrderDetailReq(purchaseOrderDetailReq, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(r) || r.getData() == null) {
            throw new ErrorDataException("关联采购单明细出错");
        }
        PurchaseOrderDetail orderDetail = BeanUtil.toBean(r.getData(), PurchaseOrderDetail.class);
        //设置采购数量
        offerOrder.setBuyNum(orderDetail.getNeedBuyNum());
        //采购价格
        offerOrder.setSupplyPrice(orderDetail.getBuyPrice());
        //询价时间
        offerOrder.setAskPriceTime(orderDetail.getCreateDate());
        //单位
        offerOrder.setUnit(orderDetail.getUnit());

        return offerOrder;
    }


}
